package com.health.system.service.lmpl;

import com.alibaba.nacos.api.model.v2.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.common.core.utils.StringUtils;
import com.health.system.domain.po.TvideoPo;
import com.health.system.domain.vo.TvideoVo;
import com.health.system.mapper.TvideoMapper;
import com.health.system.service.TvideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xpz
 * @date 2024/12/16 19:52
 */
@Service
@Slf4j
public class TvideoServicelmpl implements TvideoService{

    @Autowired
    private TvideoMapper tvideoMapper;

    private static final String CACHE_KEY_PREFIX = "videoId";

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public List<TvideoPo> videoList(TvideoVo tvideoVo) {
        List<TvideoPo> list = tvideoMapper.videoList(tvideoVo);
        return list;
    }

    @Override
    public Result videoAdd(TvideoPo tvideoPo) {
        if (StringUtils.isEmpty(tvideoPo.getAmount())){
            return Result.failure("视频价格不能为空");
        }
        if (StringUtils.isEmpty(tvideoPo.getTitle())){
            return Result.failure("视频标题不能为空");
        }
        if (StringUtils.isEmpty(tvideoPo.getContent())){
            return Result.failure("视频内容不能为空");
        }
        tvideoMapper.videoAdd(tvideoPo);
        return Result.success();
    }

    @Override
    public Result updateById(TvideoPo tvideoPo) {
        if (StringUtils.isEmpty(tvideoPo.getAmount())){
            return Result.failure("视频价格不能为空");
        }
        if (StringUtils.isEmpty(tvideoPo.getTitle())){
            return Result.failure("视频标题不能为空");
        }
        if (StringUtils.isEmpty(tvideoPo.getContent())){
            return Result.failure("视频内容不能为空");
        }
        tvideoMapper.updateById(tvideoPo);
        return Result.success();
    }

    @Override
    public void removeById(Integer id) {
        String cacheKey=CACHE_KEY_PREFIX+id;
        //第一次删除缓存 在操作数据库之前
        redisTemplate.delete(cacheKey);
        try {
            int i = tvideoMapper.removeByIdDelete(id);
            if (i>0){
                // 第二次删除缓存（在数据库操作之后）
                redisTemplate.delete(cacheKey);
                log.info("视频信息删除成功: {}", id);
            }else {
                log.warn("视频信息删除失败，未找到要删除的记录: {}", id);
            }
        } catch (Exception e) {
            log.error("视频信息删除失败，错误信息：{}", e.getMessage(), e);

        }
    }


}
